<?php

/**
 * This is the model class for table "{{file}}".
 *
 * The followings are the available columns in table '{{file}}':
 * @property integer $id
 * @property string $title
 * @property string $picture
 * @property string $description
 * @property string $create_date
 * @property string $created_by
 * @property string $update_date
 * @property string $updated_by
 * @property integer $hits
 */
class FileModel extends CActiveRecord {

    const MAX_FILE_SIZE = 10485760; //10Mb
    const SCENARIO_SEARCH = 'search';
    const SCENARIO_CREATE = 'create';
    const SCENARIO_UPDATE = 'update';

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return FileModel the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{file}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	// NOTE: you should only define rules for those attributes that
	// will receive user inputs.
	return array(
	    array('title', 'required'),
	    array('hits', 'numerical', 'integerOnly' => true),
	    array('title', 'length', 'max' => 100),
	   // array('picture', 'required', 'on' => Album::SCENARIO_CREATE, 'message' => t('MSG_REQUIRED', 'messages')),
	    array('picture', 'length', 'max' => 255, 'tooLong' => t('MSG_STRING_TOO_LONG', 'messages'), 'on' => 'create'),
	    array('picture', 'file', 'types' => 'pdf,doc,docx,xlsx,xls', 'maxSize' => self::MAX_FILE_SIZE, // 10MB
		'tooLarge' => t('MSG_FILE_TOO_LARGE', 'messages'),
		'wrongType' => t('MSG_FILE_WRONG_TYPE', 'messages'),
		'allowEmpty' => false, 'on' => Album::SCENARIO_CREATE),
	     //array('picture, picture', 'required', 'on' => Album::SCENARIO_CREATE),
	    array('picture', 'file', 'types' => 'pdf,doc,docx,xlsx,xls', 'maxSize' => self::MAX_FILE_SIZE, // 10MB
		'tooLarge' => t('MSG_FILE_TOO_LARGE', 'messages'),
		'wrongType' => t('MSG_FILE_WRONG_TYPE', 'messages'),
		'allowEmpty' => true, 'on' => Album::SCENARIO_UPDATE),
	    
	    array('description', 'length', 'max' => 1000),
	    // The following rule is used by search().
	    // Please remove those attributes that should not be searched.
	    array('id, title, picture, description, hits', 'safe', 'on' => 'search'),
	);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
	// NOTE: you may need to adjust the relation name and the related
	// class name for the relations automatically generated below.
	// NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'userAndFiles' => array(self::HAS_MANY, 'UserAndFile', 'file_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'id' => t('LBL_ID', 'fileModel'),
	    'title' => t('LBL_TITLE', 'fileModel'),
	    'picture' => t('LBL_FILE', 'fileModel'),
	    'description' => t('LBL_DESCRIPTION', 'fileModel'),
	    'create_date' => t('LBL_CREATE_DATE', 'fileModel'),
	    'created_by' => t('LBL_CREATED_BY', 'fileModel'),
	    'update_date' => t('LBL_UPDATE_DATE', 'fileModel'),
	    'updated_by' => t('LBL_UPDATED_BY', 'fileModel'),
	    'hits' => t('LBL_HITS', 'fileModel'),
	);
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
	// Warning: Please modify the following code to remove attributes that
	// should not be searched.

	$criteria = new CDbCriteria;

	$criteria->compare('id', $this->id);
	$criteria->compare('title', $this->title, true);
	$criteria->compare('picture', $this->picture, true);
	$criteria->compare('description', $this->description, true);
	$criteria->compare('create_date', $this->create_date, true);
	$criteria->compare('created_by', $this->created_by, true);
	$criteria->compare('update_date', $this->update_date, true);
	$criteria->compare('updated_by', $this->updated_by, true);
	$criteria->compare('hits', $this->hits);

	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	));
    }

    public function beforeSave() {
	if (parent::beforeSave()) {
	    $current_date = date(LGConstant::DATE_FORMAT_FOR_DATABASE);
	    $logedInUser = User::model()->findByPk(Yii::app()->user->id);

	    if ($this->isNewRecord) {
		$this->create_date = $current_date;
		$this->created_by = $logedInUser->username;
	    }

	    $this->update_date = $current_date;
	    $this->updated_by = $logedInUser->username;

	    return true;
	}
	else
	    return false;
    }

    protected function afterFind() {
	// convert to display format
	$this->update_date = strtotime($this->update_date);
	$this->update_date = date(LGConstant::DATE_FORMAT, $this->update_date);
	if ($this->update_date == LGConstant::DATE_DEFAULT)
	    $this->update_date = '';
	parent::afterFind();
    }

    protected function afterDelete() {
	$path = FILE_FOLDER . DS . $this->picture;
	if (file_exists($path)) {
	    unlink($path);
	}

	parent::afterDelete();
    }

    public static function findAllFilesWithFileAllViewRoles ($pageSize = null) {
	$criteria = new CDbCriteria();
	$criteria->with = array ('userAndFiles', 'userAndFiles.user');
	$criteria->order = 'id DESC';
	
	$model = self::model();
	if (!isset($pageSize)) {
	    $pageSize = $model->count($criteria);
	}
	return new CActiveDataProvider($model, array(
	    'criteria' => $criteria,
	    'pagination' => array(
		'pageSize' => $pageSize,
	    ),
	));
	    
    }
    
     public static function findAllFilesWithUserID ($userID, $pageSize = null) {
	$criteria = new CDbCriteria();
	$criteria->with = array ('userAndFiles');
	$criteria->compare('userAndFiles.user_id', $userID);
	$criteria->together = true;
	$criteria->order = 'userAndFiles.id DESC';
	
	$model = self::model();
	
	if (!isset($pageSize)) {
	    $pageSize = $model->count($criteria);
	}
	return new CActiveDataProvider($model, array(
	    'criteria' => $criteria,
	    'pagination' => array(
		'pageSize' => $pageSize,
	    ),
	));
	    
    }
    
    
}